<?php
namespace core\basic;
class Thy {
    public static function run() {
        // 加载数据库配置文件
        $config = require CONF_PATH . '/database.php';
        // 获取数据库连接参数
        $dbConfig = $config['database'];
        $host = $dbConfig['host'];
        $user = $dbConfig['user'];
        $pass = $dbConfig['passwd'];
        $dbname = $dbConfig['dbname'];
        $port = $dbConfig['port'];

        // 创建数据库连接
        try {
            $pdo = new \PDO("mysql:host=$host;port=$port;dbname=$dbname", $user, $pass);
            $pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
        } catch (\PDOException $e) {
            die("数据库连接失败: " . $e->getMessage());
        }

        // 获取当前域名
        $domain = $_SERVER['HTTP_HOST'];

        // 生成授权码的函数
        function generateAuthorizationCode($domain) {
            $sha1_domain = substr(sha1($domain), 0, 10);
            return strtoupper(substr(md5($sha1_domain), 10, 10));
        }

        // 处理主域名和子域名的授权码生成
        $authCodes = [];
        $mainDomain = preg_replace('/^www\./', '', $domain); // 去除 www. 前缀
        if (preg_match('/^[^\.]+\.[^\.]+$/', $mainDomain)) {
            // 主域名（没有子域名的域名）
            $authCodes[] = generateAuthorizationCode($mainDomain);
            $authCodes[] = generateAuthorizationCode('www.' . $mainDomain);
        } else {
            // 非主域名（带有子域名）
            $authCodes[] = generateAuthorizationCode($domain);
        }

        // 将 $authCodes 数组转换为逗号分隔的字符串
        $authCodesStr = implode(',', $authCodes);

        // 查询数据库中name为'sn'的记录
        $sql = "SELECT value FROM ay_config WHERE name = 'sn'";
        $stmt = $pdo->prepare($sql);
        $stmt->execute();
        $result = $stmt->fetch();

        if ($result) {
            // 获取'sn'对应的value
            $value = $result['value'];
            // 检查授权码是否已存在于value中
            if (strpos($value, $authCodesStr) === false) {
                // 如果不存在，则将授权码追加到value中
                $newValue = $value ? $value . ',' . $authCodesStr : $authCodesStr;
                // 更新数据库
                $updateSql = "UPDATE ay_config SET value = :value WHERE name = 'sn'";
                $updateStmt = $pdo->prepare($updateSql);
                $updateStmt->execute(['value' => $newValue]);

                // 生成 licensecode
                $licensecode = base64_encode($newValue . '/' . '') . substr($newValue, 1, 1);
                $updateLicensecodeSql = "UPDATE ay_config SET value = :value WHERE name = 'licensecode'";
                $updateLicensecodeStmt = $pdo->prepare($updateLicensecodeSql);
                $updateLicensecodeStmt->execute(['value' => $licensecode]);
                path_delete(RUN_PATH . '/config'); // 清理缓存的配置文件
            }
        }
    }
}
?>
